package init

import (
	"api/basic/conSul"
	"api/basic/global"
	__ "api/basic/proto"
	"flag"
	"fmt"
	"github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
)

func init() {
	InitGrpc()
	InitConsul()
}

func InitConsul() {
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", "14.103.149.201", 8500)
	client, err := api.NewClient(config)
	if err != nil {
		return
	}
	global.ConsulClient = client
	newClient := conSul.NewConsul("127.0.0.1", 8901)
	filterConsul, err := newClient.FilterConsul("good")
	if err != nil {
		return
	}
	if len(filterConsul) == 0 {
		fmt.Println("service not found conSul register service:")

		// gRPC健康检查配置
		grpcCheck := &api.AgentServiceCheck{
			GRPC:                           "14.0.3.149.201:8500", // 修改为外部 IP 地址
			Interval:                       "15s",                 // 健康检查间隔
			Timeout:                        "5s",                  // 超时时间
			DeregisterCriticalServiceAfter: "30m",                 // 故障30分钟后注销服务
		}

		// 注册到 Consul
		err = newClient.RegisterConsulWithCheck("good", "127.0.0.1", 8901, []string{"good"}, grpcCheck)
		if err != nil {
			fmt.Println("consul注册失败")
		} else {
			fmt.Println("consul注册成功")
		}
	} else {
		fmt.Println("服务已经注册到consul")
	}

	services, err := newClient.GetConsulServices()
	if err != nil {
		fmt.Println("获取服务失败", err)
		return
	}
	// 打印服务地址和端口
	if len(services) == 0 {
		fmt.Println("没有找到注册的服务")
	} else {
		for _, service := range services {
			fmt.Printf("服务ID: %s, 地址: %s, 端口: %d\n", service.Service, service.Address, service.Port)
		}
	}
}

func InitGrpc() {
	flag.Parse()
	// Set up a connection to the server.
	conn, err := grpc.NewClient("127.0.0.1:8901", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}

	global.S = __.NewGoodServerClient(conn)
}
